package com.iwat.spring.aop.service.impl;

import com.iwat.spring.aop.constant.RedisKey;
import com.iwat.spring.aop.entity.SysLog;
import com.iwat.spring.aop.service.LogService;
import com.iwat.spring.aop.util.RedisBlockingQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @Author wangweiqiang
 * @Classname LogServiceImpl
 * @Date 2023/9/23 10:52
 * @Description
 */
@Service
@Slf4j
public class LogServiceImpl implements LogService {

    @Autowired
    private RedisBlockingQueue<SysLog> redisBlockingQueue;

    /**
     * 消费redis阻塞队列中值，启动时执行一次
     */
    @Scheduled(fixedRate = Long.MAX_VALUE)
    public void save() {
        while (true){
            SysLog sysLog = null;
            try {
                sysLog = redisBlockingQueue.dequeue(RedisKey.LOG_MESSAGE);
            } catch (Exception e) {
                log.error("从redis阻塞队列中获取日志消息失败", e);
            }
            //todo 保存到数据库
            System.out.println("消费一条日志："+sysLog);
        }
    }

    @Override
    public void save(SysLog sysLog) {
        redisBlockingQueue.enqueue(RedisKey.LOG_MESSAGE, sysLog);
    }
}
